package com.jhw.exception;

import com.jhw.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jhw
 * @create 2022/9/24
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 捕捉全局异常
    @ExceptionHandler(value = Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JSONResult.error(GlobalErrorCode.ERROR);
    }
    // 自定义异常
    @ExceptionHandler(value = GlobalCustomException.class)
    public JSONResult GlobalCustomExceptionHandler(GlobalCustomException e){
        e.printStackTrace();
        // 2.返回异常信息
        return JSONResult.error(e.getErrorMessage(), e.getErrorCode());
    }

    // 捕捉参数异常。并将message提出来
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return JSONResult.error(message);
    }

}
